package com.cat.binaryAnswer;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/compare-strings-by-frequency-of-the-smallest-character/
 * @create 2025/8/9 19:44
 * @since JDK17
 */

public class Solution03 {
    int f(String s) {
        int[] h = new int[26];
        int ans = 0, n = s.length();
        for (int i = 0; i < n; i++) {
            h[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < 26; i++) {
            if (h[i] != 0) {
                return h[i];
            }
        }
        return 0;
    }

    // 找到第一个更大的
    int find(int[] h, int target) {
        int l = -1, r = h.length, mid;
        while (l + 1 < r) {
            mid = l + (r - l) / 2;
            if (h[mid] > target) {
                r = mid;
            } else {
                l = mid;
            }
        }
        return r;
    }

    public int[] numSmallerByFrequency(String[] queries, String[] words) {
        int n = queries.length, m = words.length;
        int[] ans = new int[n], h1 = new int[n], h2 = new int[m];
        for (int i = 0; i < n; i++) {   //
            h1[i] = f(queries[i]);
        }

        for (int i = 0; i < m; i++) {
            h2[i] = f(words[i]);
        }
        Arrays.sort(h2);
        for (int i = 0; i < n; i++) {   //
            ans[i] = m - find(h2, h1[i]);
        }

        return ans;
    }
}
